package org.duang.sms.utils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.duang.config.Config;
import org.duang.kit.ToolsKit;
import org.duang.sms.core.SmsMessage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class SmsToolsKit {

	private final static String QUOTATION = "\"";
	private final static Map<String, SmsMessage> templateMap = new HashMap<String, SmsMessage>();

	/**
	 * 通过反射创建实例
	 */
	@SuppressWarnings("unchecked")
	public static <T> T newInstance(String className) {
		T instance;
		try {
			Class<?> commandClass = Class.forName(className);
			instance = (T) commandClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return instance;
	}

	public static String toJsonString(Map<String, String> map) {
		if (null == map) {
			throw new NullPointerException("map is null");
		}
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		for (Iterator<Entry<String, String>> it = map.entrySet().iterator(); it.hasNext();) {
			Entry<String, String> entry = it.next();
			sb.append(QUOTATION).append(entry.getKey()).append(QUOTATION).append(":").append(QUOTATION)
					.append(entry.getValue()).append(QUOTATION).append(",");
		}
		if (sb.length() > 1) {
			sb.deleteCharAt(sb.length() - 1);
		}
		sb.append("}");
		return sb.toString();
	}

	public static String builderPhones(List<String> phoneList, int max) {
		if (null == phoneList) {
			throw new NullPointerException("phoneList is null");
		}
		if (phoneList.size() > max) {
			throw new IndexOutOfBoundsException();
		}
		StringBuilder sb = new StringBuilder();
		for (Iterator<String> it = phoneList.iterator(); it.hasNext();) {
			sb.append(it.next()).append(",");
		}
		if (sb.length() > 1) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	private static String getSmsTemplateJson() {
		String urlStr = Config.getSmsTemplateUrl();
		InputStream input = null;
		HttpURLConnection connection = null;
		String json = "";
		try {
			URL url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.connect();
			input = connection.getInputStream();
			json = IOUtils.toString(input, Config.getCharEncode());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(input);
			connection.disconnect();
		}
		return json;
	}

	@SuppressWarnings("rawtypes")
	private static Map<String, SmsMessage> getTemplateCodeMap() {
		try {
			String json = getSmsTemplateJson();
			if (json.isEmpty()) {
				throw new NullPointerException("sms_template.json is null");
			}
			Map<String, SmsMessage> tempMap = new HashMap<String, SmsMessage>();
			JSONArray array = JSON.parseArray(json);
			for (Iterator it = array.listIterator(); it.hasNext();) {
				JSONObject obj = (JSONObject) it.next();
				String type = obj.getString("type");
				String tplCode = obj.getString("tplcode");
				String text = obj.getString("text");
				String name = obj.getString("name");
				SmsMessage message = new SmsMessage();
				message.setText(text);
				message.setTplCode(tplCode);
				message.setName(name);
				message.setType(type);
				tempMap.put(type, message);
			}
			return tempMap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static SmsMessage builderSmsMessage(String type) {
		if (ToolsKit.isEmpty(templateMap) || ToolsKit.isEmpty(templateMap.get(type))) {
			Map<String, SmsMessage> map = getTemplateCodeMap();
			if (null != map) {
				templateMap.putAll(map);
			}
		}
		return templateMap.get(type);
	}

	/**
	 * 重载模板数据
	 * 
	 * @throws Exception
	 */
	public static void reloadTemplate() throws Exception {
		Map<String, SmsMessage> map = getTemplateCodeMap();
		if (null != map) {
			templateMap.clear();
			templateMap.putAll(map);
		}
	}

	public static String builderContent(SmsMessage message) {
		String content = message.getText();
		for (Iterator<Entry<String, String>> it = message.getParams().entrySet().iterator(); it.hasNext();) {
			Entry<String, String> entry = it.next();
			content = content.replace( Config.getSmsTemplateReplaceKey().replace("_#_", entry.getKey()), entry.getValue());
		}
		return content;
	}
	
	/**
	   * 替换字符串 
	   * @param from String 原始字符串  
	   * @param to String 目标字符串  
	   * @param source String 母字符串  
	   * @return String 替换后的字符串  
	*/  
	  private static String replace(String from, String to, String source) {   
	    if (source == null || from == null || to == null)   
	      return null;   
	    StringBuffer bf = new StringBuffer("");   
	    int index = -1;   
	    while ((index = source.indexOf(from)) != -1) {   
	      bf.append(source.substring(0, index) + to);   
	      source = source.substring(index + from.length());   
	      index = source.indexOf(from);   
	    }   
	    bf.append(source);   
	    return bf.toString();   
	  }
}
